package com.xd.common.model;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.xd.common.vo.ApiErrorCode;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @author huboxin
 * @title: R
 * @projectName bk
 * @description: REST API 返回结果
 * @date 2020/8/2117:48
 */
@Data
@Accessors(chain = true)
public class R<T> extends com.baomidou.mybatisplus.extension.api.R<T> {

    private static final long serialVersionUID = -1919327270667716943L;


    /**
     * 业务错误码
     */
    private long code;
    /**
     * 结果集
     */
    private T data;
    /**
     * 描述
     */
    private String msg;

    public R() {
        // to do nothing
    }


    public R(IErrorCode errorCode) {
        super(errorCode);
    }

    public static <T> R<T> ok(T data) {
        ApiErrorCode aec = ApiErrorCode.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            aec = ApiErrorCode.FAILED;
        }
        return restResult(data, aec);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, ApiErrorCode.FAILED.getCode(), msg);
    }

    public static <T> R<T> failed(IErrorCode errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> R<T> restResult(T data, IErrorCode errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMsg());
    }

    private static <T> R<T> restResult(T data, long code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    @Override
    public boolean ok() {
        return ApiErrorCode.SUCCESS.getCode() == code;
    }



}
